#include "OgreGLESRenderSystem.h"

#include "OgreEGLSupport.h"
#include "OgreEGLContext.h"

#include "OgreRoot.h"

namespace Ogre
{
	EGLContext::EGLContext(EGLDisplay eglDisplay,
						   const EGLSupport* glsupport,
						   ::EGLConfig glconfig,
						   ::EGLSurface drawable)
		: mGLSupport(glsupport),
		  mDrawable(drawable),
		  mContext(0),
		  mConfig(glconfig),
		  mEglDisplay(eglDisplay)
	{
		assert(drawable);
		GLESRenderSystem* renderSystem =
			statci_cast<GLESRenderSystem*>(Root::getSingleton().getRenderSystem());
		EGLContext* mainContext = 
			static_cast<EGLContext*>(renderSystem->_getMainContext());
		::EGLContext shareContext = (::EGLContext)0;
		
		if (mainContext)
		{
			shareContext = mainContext->mContext;
		}
		
		mContext = mGLSupport->createNewContext(eglDisplay, mConfig, shareContext);
		
		if (!mContext)
		{
			OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
						"Unable to create a suitable EGLContext",
						"EGLContext::EGLContext");
		}
	}
	
	EGLContext::~EGLContext()
	{
		GLESRenderSystem *rs = 
			static_cast<GLESRenderSystem*>(Root::getSingleton().getRenderSystem());
			
		eglDestroyContext(mEglDisplay, mContext);
		rs->_unregisterContext(this);
	}
	
	void EGLContext::setCurrent()
	{
		EGLBoolean ret = eglMakeCurrent(mEglDisplay,
										mDrawable, mDrawable, mContext);
		
		if (!ret)
		{
			OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
						"Unable to create a suitable EGLContext",
						"EGLContext::EGLContext");
		}
	}
	
	void EGLContext::endCurrent()
	{
		eglMakeCurrent(mEglDisplay, 0, 0, 0);
	}
	
	EGLSurface EGLContext::getDrawable() const
	{
		return mDrawable;
	}
}
